import fs from "fs";
import path from "path";

// git-hooks的路径
const HOOKS_PATH = '../../../.git/hooks';

/**
 * 创建deal-svg.sh文件
 * 需要了解sh文件的语法
 */
const createDealSvgSh = () => {
  const dealSvgPath = path.join(__dirname, HOOKS_PATH, 'deal-svg.sh');
  const dealSvgContent = `#!/bin/bash
echo 处理svg...
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)

dealGitSvgPath="\${SCRIPT_DIR}/../../src/libs/deal-svg/dealGitSvg.js"

if [ -f "$dealGitSvgPath" ]; then
  cd "$(git rev-parse --show-toplevel)" || exit 1
  node "$dealGitSvgPath"
else
  echo "dealGitSvg.js不存在，跳过svg处理"
fi`;
  fs.writeFileSync(dealSvgPath, dealSvgContent, 'utf8');
  console.log('创建deal-svg.sh文件成功！');
}

try {
  // 获取预提交文件
  const preCommitPath = path.join(__dirname, HOOKS_PATH, 'pre-commit');
  if (fs.existsSync(preCommitPath)) {
    // 添加deal-svg.sh脚本命令进pre-commit中，commit提交的时候会执行
    let preCommitContent = fs.readFileSync(preCommitPath, 'utf8');
    const dealSvgLine = '\n. "$(dirname "$0")/deal-svg.sh"\n';
    if (!preCommitContent.includes(dealSvgLine)) {
      preCommitContent += dealSvgLine;
      fs.writeFileSync(preCommitPath, preCommitContent, 'utf8');
      console.log('添加deal-svg命令进pre-commit脚本成功！');
    } else {
      console.log('deal-svg命令已存在pre-commit脚本中');
    }
    // 创建deal-svg.sh脚本
    createDealSvgSh();
  }
} catch (error) {
  console.error('svg处理初始化失败：', error);
}
